﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kinect.Toolbox.Providers;
using Microsoft.Kinect;
using Microsoft.Practices.Unity;

namespace Kinect.Toolbox.Recording
{
    public class FramePlayer : IStartableStoppable
    {
        private BinaryFilesFrameProvider _binaryFilesFrameProvider;

        public event EventHandler Stopped;
        public event EventHandler Started;

        public void Start()
        {
            _binaryFilesFrameProvider = new BinaryFilesFrameProvider();
            _binaryFilesFrameProvider.NoFramesLeft += BinaryFilesFrameProviderOnNoFramesLeft;

            DependencyFactory.Container.Resolve<IToolboxEventsInvoker>().OnFrameProviderChanging();
            DependencyFactory.Container.RegisterInstance<IFrameProvider>(_binaryFilesFrameProvider, new ContainerControlledLifetimeManager());
            DependencyFactory.Container.Resolve<IToolboxEventsInvoker>().OnFrameProviderChanged();
            _binaryFilesFrameProvider.Start();

            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }
        }

        public void Stop()
        {
            _binaryFilesFrameProvider.NoFramesLeft -= BinaryFilesFrameProviderOnNoFramesLeft;

            DependencyFactory.Container.Resolve<IToolboxEventsInvoker>().OnFrameProviderChanging();
            DependencyFactory.Container.RegisterType<IFrameProvider, KinectFrameProvider>(new ContainerControlledLifetimeManager());
            DependencyFactory.Container.Resolve<IToolboxEventsInvoker>().OnFrameProviderChanged();

            _binaryFilesFrameProvider.Stop();

            if (Stopped != null)
            {
                Stopped(this, EventArgs.Empty);
            }
        }

        private void BinaryFilesFrameProviderOnNoFramesLeft(object sender, EventArgs eventArgs)
        {
            Stop();
        }
    }
}
